package com.moming.douapisdk.config;

import com.moming.douapisdk.client.DefaultDouYinClient;
import com.moming.douapisdk.client.DouYinClient;
import com.moming.douapisdk.client.SelfUseDouYinClient;
import com.moming.douapisdk.internal.util.StringUtils;
import com.moming.douapisdk.properties.DouYinProperties;
import com.moming.douapisdk.storage.DefaultConfigStorageImpl;
import com.moming.douapisdk.storage.IDouYinConfigStorage;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 自动装配服务
 * <p>
 * 直接在配置文件中配置 应用参数，参考{@link DouYinProperties}
 * 会自动装配 {@link DouYinClient} 的服务，
 * <p>直接在如下使用：
 * <blockquote><pre>
 * <code>@Autowired</code>
 * private DouYinClient client;
 * </pre></blockquote>
 *
 *
 *
 *
 * @author tianzong
 * @date 2020/7/23
 */
@Configuration
@EnableConfigurationProperties(value = DouYinProperties.class)
@Log4j2
public class DefaultDouYinClientConfig {

    @Bean
    @ConditionalOnMissingBean(DouYinClient.class)
    @ConditionalOnProperty(prefix = "spring.dou-yin", name = "is-self-use", havingValue = "false", matchIfMissing = true)
    public DouYinClient defaultDouYinClient(DouYinProperties douYinProperties) {

        log.info("create DouYinClient success---{}", douYinProperties.toString());
        IDouYinConfigStorage configStorage = new DefaultConfigStorageImpl();
        configStorage.setAppKey(douYinProperties.getAppKey());
        configStorage.setAppSecret(douYinProperties.getAppSecret());
        configStorage.setApiUrl(douYinProperties.getApiUrl());
        return new DefaultDouYinClient(configStorage);
    }

    @Bean
    @ConditionalOnMissingBean(DouYinClient.class)
    @ConditionalOnProperty(prefix = "spring.dou-yin", name = "is-self-use", havingValue = "true")
    public DouYinClient selfUseDouYinClient(DouYinProperties douYinProperties) {

        log.info("create DouYinClient success---{}", douYinProperties.toString());
        IDouYinConfigStorage configStorage = new DefaultConfigStorageImpl();
        configStorage.setAppKey(douYinProperties.getAppKey());
        configStorage.setAppSecret(douYinProperties.getAppSecret());
        configStorage.setApiUrl(douYinProperties.getApiUrl());
        if (StringUtils.isNotEmpty(douYinProperties.getShopId())) {
            configStorage.setShopId(douYinProperties.getShopId());
        }
        return new SelfUseDouYinClient(configStorage);
    }

}
